# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

import sys
import typing


def _asFilesystemBytes(path: typing.Union[bytes, str], encoding: str='') -> bytes:
	"""
	Return C{path} as a string of L{bytes} suitable for use on this system's
	filesystem.

	@param path: The path to be made suitable.
	@type path: L{bytes} or L{unicode}
	@param encoding: The encoding to use if coercing to L{bytes}. If none is
		given, L{sys.getfilesystemencoding} is used.

	@return: L{bytes}
	"""
	if isinstance(path, bytes):
		return path
	if not encoding:
		encoding = sys.getfilesystemencoding()
	return path.encode(encoding)


def _asFilesystemText(path, encoding=None):
	"""
	Return C{path} as a string of L{unicode} suitable for use on this system's
	filesystem.

	@param path: The path to be made suitable.
	@type path: L{bytes} or L{unicode}

	@param encoding: The encoding to use if coercing to L{unicode}. If none
		is given, L{sys.getfilesystemencoding} is used.

	@return: L{unicode}
	"""
	if type(path) == str:
		return path
	if encoding is None:
		encoding = sys.getfilesystemencoding()
	return path.decode(encoding)


def _coerceToFilesystemEncoding(path, newpath, encoding=None):
	"""
	Return a C{newpath} that is suitable for joining to C{path}.

	@param path: The path that it should be suitable for joining to.
	@param newpath: The new portion of the path to be coerced if needed.
	@param encoding: If coerced, the encoding that will be used.
	"""
	if type(path) == bytes:
		return _asFilesystemBytes(newpath, encoding=encoding)
	return _asFilesystemText(newpath, encoding=encoding)
